package com.fenyin.samples.study.jdk.datastruct.queue;  
  
public class ArrayCycleQueue<V> {
	//队列头指针 指向队首元素位置
	private int head;
	//队列尾指针 指向队尾元素下一位置
	private int tail;
	//数据域
	private Object[] queue;
	
	public ArrayCycleQueue(int capation){
		queue = new Object[capation+1];
		this.head = this.tail = 0;
	}
	
	/**
	 * 入队列
	 * @param value  
	 * @Description:
	 */
	public void enqueue(V value){
		if((tail+1)%queue.length == head){//队列满
			throw new IndexOutOfBoundsException("队列已满");
		}
		queue[tail] = value;
		tail = (tail+1)%queue.length;
	}
	
	/**
	 * 出队列
	 * @return  
	 * @Description:
	 */
	@SuppressWarnings("unchecked")
	public V dequeue(){
		if(head == tail){//队列空
			throw new IndexOutOfBoundsException("队列已空");
		}
		V e = (V) queue[head];
		head= (head+1)%queue.length;
		return e;
	}
	
	/**
	 * 队列大小
	 * @return  
	 * @Description:
	 */
	public int size(){
		return tail >= head?tail-head:(queue.length+tail-head);
	}
	
	public String display(){
		StringBuffer sb = new StringBuffer();
		
		for(int i=head; i!=tail;){
			sb.append(queue[i]).append("|");
			i = (i+1)%queue.length;
		}
		return sb.toString();
	}
}
